<template>
    <!--<el-row justify="space-between">
        <el-col :span="12" class="self-flex-align--center nrtitle">
            本企业内容包
        </el-col>
        <el-col :span="12" align="right">
            <el-button size="small" @click="handleDialog('PackageSave')" type="primary">创建内容包</el-button>
        </el-col>
    </el-row>-->
    <div v-loading="loading">
    <template v-if="packageList && packageList.length > 0">
        <el-row :gutter="20" v-for="(infos,indexs) in packageList" :key="indexs">
            <el-col :span="8" v-for="(info,innerindex) in infos" :key="innerindex">
                <el-card class="box-card">
                        <span v-if="info.inuse == 1" class="biao">
                            <span>上线</span>
                        </span>
                        <!-- <span v-else>
                            <span>下线</span>
                        </span> -->
                    <el-row justify="end">
                        <!--<span>
                            <el-button type="text" size="mini" @click="handleDialog('PackageEdit',{packageid:info.packageid})">编辑</el-button>
                            <el-button type="text" v-if="info.inuse == 1" size="mini" @click="handleSetInuse(info.name, info.packageid, 0)">下线</el-button>
                            <el-button type="text" v-else size="mini" @click="handleSetInuse(info.name, info.packageid, 1)">上线</el-button>
                        </span>-->
                        <el-dropdown @command="handlePackageCommand">
                            <span class="el-dropdown-link">
                                <el-icon style="cursor:pointer;"><more-filled /></el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <!--<el-dropdown-item v-if="info.inuse == 1" :command="beforeHandleCommand('shareable',info)">分享</el-dropdown-item>-->
                                    <el-dropdown-item v-if="info.inuse == 1" :command="beforeHandleCommand('writable',info)">开放写入权限</el-dropdown-item>
                                    <el-dropdown-item :command="beforeHandleCommand('setting',info)">内容包设置</el-dropdown-item>
                                    <el-dropdown-item v-if="info.inuse == 1" :command="beforeHandleCommand('offline',info)">下线</el-dropdown-item>
                                    <el-dropdown-item v-if="info.inuse == 0" :command="beforeHandleCommand('online',info)">上线</el-dropdown-item>
                                    <el-dropdown-item :command="beforeHandleCommand('mediatype',info)">自动写入设置</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </el-row>
                    <div class="packagebox">
                    <div class="pktitle">{{info.name}}</div>
                    <div class="pkinfo">
                        <div>原包ID：{{info.ppackageid != -1 ? info.ppackageid : '-'}}</div>
                        <div>内容包ID：{{info.packageid}}</div>
                        <div>包含媒资：{{info.mediacount}}</div>
                        <div>创建时间：{{info.ctime?info.ctime:'-'}}</div>
                        <div>最后更新：{{info.mtime?info.mtime:'-'}}</div>
                    </div>
                    <div class="btn-control"><el-button  type="primary" class="btn-nr" @click="handleContent(info.packageid)">内容管理</el-button></div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </template>
    <template v-else-if="packageList && packageList.length == 0 && !loading">
        <el-empty description="暂无内容包，快快创建吧"></el-empty>
    </template>
    </div>
    <component
        :is="asyncComponentPackageSave"
        :visible="dialogVisible.PackageSave"
        :toDialogData="toPackageSaveDialogData"
        @cancelDialog="cancelDialog"
        :key="toPackageSaveDialogData.dialogKey"
    />
    <component
        :is="asyncComponentPackageShare"
        :title="dialogTitle"
        :visible="dialogVisible.PackageShare"
        :toDialogData="toDialogData"
        @cancelDialog="cancelDialog"
        :key="toPackageSaveDialogData.dialogKey"
    />
    <component
        :is="asyncComponentPackageWrite"
        :title="dialogTitle"
        :visible="dialogVisible.PackageWrite"
        :toDialogData="toDialogData"
        @cancelDialog="cancelDialog"
        :key="toPackageSaveDialogData.dialogKey"
    />
    <component
        :is="asyncComponentPackageMediatype"
        :title="dialogTitle"
        :visible="dialogVisible.PackageMediatype"
        :toDialogData="toDialogData"
        @cancelDialog="cancelDialog"
        :key="toPackageSaveDialogData.dialogKey"
    />
</template>

<script>
    import { useRouter } from 'vue-router';
    import { getPackages } from '@/api/package/package'
    import {useStore} from 'vuex'
    import {ref,reactive,defineAsyncComponent} from 'vue'
    import { updatePackage } from "@/api/package/package"
    import {ElMessage,ElMessageBox} from 'element-plus'
    export default {
        name: "",
        components: {
            "PackageSave" : defineAsyncComponent(() => import('../components/dialogs/PackageCreate')),
            "PackageShare" : defineAsyncComponent(() => import('../components/dialogs/PackageShareDialog')),
            "PackageWrite" : defineAsyncComponent(() => import('../components/dialogs/PackageWriteDialog')),
            "PackageMediatype" : defineAsyncComponent(() => import('../components/dialogs/PackageMediatypeDialog')),
        },
        setup() {
            const router = useRouter()
            const store = useStore()
            const corpid = store.getters.corpinfo.corpid
            const subid = store.getters.subinfo.subid
            const loading = ref(true)

            const packageList = ref([])
            const getPackageData = () => {
                loading.value = true
                packageList.value = []
                getPackages({'corpid':corpid,'subid':subid}).then(response => {
                    loading.value = false
                    // console.log(response)
                    if( response.errcode == 0 && response.data.list.length > 0 ){
                        response.data.list.forEach((value,index) => {
                            const pindex = Math.floor(index/3)
                            if( !packageList.value[pindex] ){
                                packageList.value[pindex] = []
                            }
                            packageList.value[pindex].push(value)
                        });
                        // console.log(packageList)
                    }else{
                        console.log(response)
                    }
                })
            }
            
            //内容包添加编辑数据
            const toPackageSaveDialogData = ref({
                'action': 'add',
                'dialogKey': ''
            })

            // 弹窗相关
            const asyncComponentPackageSave = ref(null)
            const asyncComponentPackageShare = ref(null)
            const asyncComponentPackageWrite = ref(null)
            const asyncComponentPackageMediatype = ref(null)
            const dialogTitle = ref(null)
            const dialogVisible = ref({
                PackageSave: false,
                PackageShare: false,
                PackageWrite: false,
                PackageMediatype: false,
            })
            const toDialogData = reactive({})
            const cancelDialog = ( dialogName, optiontype ) => {
                /*
                    optiontype:
                    1:刷新列表
                */
                switch ( dialogName ){
                    case 'PackageSave':
                        dialogVisible.value.PackageSave = false
                        if( optiontype == 1 ){
                            getPackageData()
                        }
                        break;
                    case 'PackageShare':
                        dialogVisible.value.PackageShare = false
                        break;
                    case 'PackageWrite':
                        dialogVisible.value.PackageWrite = false
                        break;
                    case 'PackageMediatype':
                        dialogVisible.value.PackageMediatype = false
                        break;
                }
            }

            /*const handleSetInuse = (packagename, packageid, inuseVal) => {
                let elMsg = ''
                let inputPlac = ''
                if( inuseVal == 0 ){
                    elMsg = '确定 <strong>'+ packagename + '</strong> 进行下线操作吗？'
                    inputPlac = '请输入下线原因（必填）'
                }else{
                    elMsg = '确定 <strong>'+ packagename + '</strong> 进行上线操作吗？'
                    inputPlac = '请输入上线原因（选填）'
                }
                ElMessageBox.prompt(elMsg, '内容包上下线', {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: (val) => {
                        if (inuseVal == 0 && val === null) {
                            return false;//初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
                        }else{
                            return true;
                        }
                    },
                    inputPlaceholder:inputPlac,
                    inputErrorMessage: '请输入下线原因',
                }).then(() => {
                    updatePackage({packageid:packageid,inuse:inuseVal}).then(response => {
                        if(response.errcode == 0){
                            ElMessage({type: 'success', message: response.msg, duration: 2000})
                            getPackageData()
                        }else{
                            console.log(response)
                        }
                    })
                }).catch((err) => {
                    console.log(err)
                })

            }*/

            const handleContent = (packageid) => {
                router.push({name:'packagecontent',query: {packageid:packageid}})
            }
            const init = () => {
                getPackageData()
            }

            // 下拉框功能
            const beforeHandleCommand = (item,row) => {
                return {
                    'command': item,
                    'packageInfo': row
                }
            }
            const handlePackageCommand = (command) => {
                toPackageSaveDialogData.value.dialogKey = new Date().getTime()
                switch(command.command){
                    case 'shareable':
                        asyncComponentPackageShare.value = 'PackageShare'
                        dialogTitle.value = '内容包分享'
                        dialogVisible.value.PackageShare = true
                        toDialogData.package = command.packageInfo
                        // console.log('shareable',command.packageInfo.packageid)
                        break
                    case 'writable':
                        asyncComponentPackageWrite.value = 'PackageWrite'
                        dialogTitle.value = '向合作企业开放写入权限'
                        dialogVisible.value.PackageWrite = true
                        toDialogData.package = command.packageInfo
                        break
                    case 'mediatype':
                        asyncComponentPackageMediatype.value = 'PackageMediatype'
                        dialogTitle.value = '自动写入设置'
                        dialogVisible.value.PackageMediatype = true
                        toDialogData.package = command.packageInfo
                        break
                    case 'setting':
                        asyncComponentPackageSave.value = 'PackageSave'
                        dialogVisible.value.PackageSave = true
                        toPackageSaveDialogData.value.action = 'edit'
                        toPackageSaveDialogData.value.packageid = command.packageInfo.packageid
                        toPackageSaveDialogData.value.corpid = corpid
                        break
                    // 默认处理上下线
                    default :{
                        let elMsg = ''
                        let inputPlac = ''
                        if( command.command == 'offline' ){
                            elMsg = '确定 <strong>'+ command.packageInfo.name + '</strong> 进行下线操作吗？'
                            inputPlac = '请输入下线原因（必填）'
                        }else if( command.command == 'online' ){
                            elMsg = '确定 <strong>'+ command.packageInfo.name + '</strong> 进行上线操作吗？'
                            inputPlac = '请输入上线原因（选填）'
                        }
                        ElMessageBox.prompt(elMsg, '内容包上下线', {
                            dangerouslyUseHTMLString: true,
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputValidator: (val) => {
                                if (command.command == 'offline' && val === null) {
                                    return false;//初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
                                }else{
                                    return true;
                                }
                            },
                            inputPlaceholder:inputPlac,
                            inputErrorMessage: '请输入下线原因',
                        }).then(() => {
                            let query = {packageid:command.packageInfo.packageid,inuse:0}
                            if( command.command == 'online' ){
                                query.inuse = 1
                            }
                            updatePackage(query).then(response => {
                                if(response.errcode == 0){
                                    ElMessage({type: 'success', message: response.msg, duration: 2000})
                                    getPackageData()
                                }else{
                                    console.log(response)
                                }
                            })
                        }).catch((err) => {
                            console.log(err)
                        })
                        break
                    }
                }
            }
            return {
                loading,
                packageList,
                toPackageSaveDialogData,
                //handleDialog,
                cancelDialog,
                asyncComponentPackageSave,
                asyncComponentPackageShare,
                asyncComponentPackageWrite,
                asyncComponentPackageMediatype,
                dialogTitle,
                dialogVisible,
                toDialogData,
                //handleSetInuse,
                handleContent,
                init,
                beforeHandleCommand,
                handlePackageCommand
            }
        }
    }
</script>

<style scoped  lang="scss">
    /* el-row-start */
    .el-button__text--expand{letter-spacing: 0;margin-right: 0;}
    .nrtitle{font-size:20px;font-weight: 600;}
    .el-row {
        margin-bottom: 20px;
        // padding-right: 20px;
        &:last-child {
            margin-bottom: 0;
        }
    }
    .el-col {
        position: relative;
        border-radius: 4px;
    }
    .bg-purple-dark {
    background: #99a9bf;
    }
    .bg-purple {
    background: #d3dce6;
    }
    .bg-purple-light {
    background: #e5e9f2;
    }
    .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
    }
    /* el-row-end */
    .self-flex-align--center {
        display: flex;
        align-items: center;
    }
    .box-card{
        .el-row{
            margin-bottom:0;
            span{
                .el-button{color:#333 !important;font-size: 14px !important;}
            }
        }
    }
    .packagebox{
        margin: auto;
        width:80%;
        .pktitle{
            font-size: 18px;
            color:#333;
            font-weight: 600;
        }
        .pkinfo{
            margin:15px auto 30px;
            font-size: 14px;
            color:#666;
            >div{
                margin-top: 10px;
            }
            >div:first-child{margin-top: 0;}
        }
        .btn-control{
            text-align: center;
            .btn-nr{
                margin:0 auto 16px;
                width:60%;
            }
        }

    }
    .biao{
        position:absolute;
        top: -3px;
        left:8px;
        width:58px;
        height:58px;
        line-height: 20px;
        color:#fff;
        font-size: 12px;
        background: url('~@/assets/img/icon_01.png') center no-repeat;
        background-size: 100%;
        >span{
            -moz-transform: rotate(-45deg);
            -webkit-transform: rotate(-45deg);
            transform: rotate(-45deg);
            display: block;
            filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3)
        }
    }
</style>
